<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800">
    <span>
      <el-form
        :model="form"
        label-width="140px"
        ref="formRef"
        :rules="rules"
        style="width: 600px"
      >
        <!-- <el-form-item label="id">
          <el-input v-model="form.id" />
        </el-form-item> -->
        <el-form-item label="配置名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" :rows="4" v-model="form.description" />
        </el-form-item>
        <el-form-item label="选择路由">
          <el-select v-model="form.routeId" placeholder="请选择">
            <el-option
              v-for="(item, indexName) in optionsRouter"
              :key="indexName"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="限流类型">
          <el-button
            :type="selectedType === 'limit-req' ? 'primary' : 'default'"
            @click="selectType('limit-req')"
          >
            QPS
          </el-button>
          <el-button
            :type="selectedType === 'limit-coon' ? 'primary' : 'default'"
            @click="selectType('limit-coon')"
          >
            线程数
          </el-button>
        </el-form-item>
        <template v-if="selectedType === 'limit-req'">
          <el-form-item label="Rate" prop="rate">
            <el-input v-model="form.rate"></el-input>
          </el-form-item>
          <el-form-item label="Burst" prop="burst">
            <el-input v-model="form.burst"></el-input>
          </el-form-item>
          <el-form-item label="Key" prop="key">
            <el-input v-model="form.key"></el-input>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="Conn" prop="conn">
            <el-input v-model="form.conn"></el-input>
          </el-form-item>
          <el-form-item label="Burst" prop="burst">
            <el-input v-model="form.burst"></el-input>
          </el-form-item>
          <el-form-item label="Default Conn Delay" prop="default_conn_delay">
            <el-input v-model="form.default_conn_delay"></el-input>
          </el-form-item>
          <el-form-item label="Key" prop="key">
            <el-input v-model="form.key"></el-input>
          </el-form-item>
        </template>
      </el-form>
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="SubmitEvent"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, computed, onMounted, ref } from "vue";
import { addFlowControlItem, editFlowControItem } from "@/api/flowControl";
import { useAppStoreHook } from "@/store/modules/app";
import { optionsGray, flowControlConversion } from "./const";
import { ElMessage } from "element-plus";
import { cloneDeep } from "lodash";
import { getRouterManagerList } from "@/api/routeManager";

const appStore = useAppStoreHook();
const emit = defineEmits(["update:modelValue", "update:list"]);
const optionsRouter = ref([]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  detailData: {
    type: Object as () => any,
    default: () => ({})
  },
  operateType: {
    type: String,
    default: "create"
  }
});
const formRef = ref(null);

const selectedType = ref("limit-req");
const dialogTitle = computed(() => {
  let title = "";
  switch (props.operateType) {
    case "create":
      title = "添加流控";
      break;
    case "edit":
      title = "配置流控";
      break;
    default:
      break;
  }
  return title;
});
// 新增分配
const isCreate = computed(() => {
  return props.operateType === "create";
});

const form = reactive({
  id: "",
  name: "",
  description: "描述",
  routeId: "",
  rate: 0,
  burst: 0,
  key: 0,
  conn: 0,
  default_conn_delay: 0
});

const dialogVisible = computed({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit("update:modelValue", val);
  }
});

const rules = reactive({
  rate: [
    {
      required: selectedType.value === "limit-req",
      message: "Rate is required",
      trigger: "blur"
    }
  ],
  burst: [{ required: true, message: "Burst is required", trigger: "blur" }],
  key: [{ required: true, message: "Key is required", trigger: "blur" }],
  conn: [
    {
      required: selectedType.value === "limit-coon",
      message: "Conn is required",
      trigger: "blur"
    }
  ],
  default_conn_delay: [
    {
      required: selectedType.value === "limit-coon",
      message: "Default Conn Delay is required",
      trigger: "blur"
    }
  ]
});

const selectType = type => {
  selectedType.value = type;
};

const SubmitEvent = async () => {
  console.log(appStore.userInfo, "appStore.userInfo");
  if (formRef.value) {
    (formRef.value as any).validate(async (valid: boolean) => {
      if (valid) {
        let flowControlConfig = cloneDeep({});
        if (selectedType.value === "limit-req") {
          flowControlConfig = {
            rate: Number(form.rate),
            burst: Number(form.burst),
            key: form.key
          };
        } else {
          flowControlConfig = {
            conn: Number(form.conn),
            burst: Number(form.burst),
            default_conn_delay: Number(form.default_conn_delay),
            key: form.key
          };
        }

        if (isCreate.value) {
          let params: any = {
            name: form.name,
            description: form.description,
            routeId: form.routeId,
            type: selectedType.value,
            operatorId: 100,
            flowControlConfig: flowControlConfig
          };
          let res = await addFlowControlItem(params);
        } else {
          let params: any = {
            id: form.id,
            name: form.name,
            description: form.description,
            routeId: form.routeId,
            type: selectedType.value,
            operatorId: 100,
            flowControlConfig: flowControlConfig
          };
          let res = await editFlowControItem(params);
        }
        ElMessage.success("提交成功");
        dialogVisible.value = false;
        emit("update:list", true);
      } else {
        ElMessage.error("请填写所有必填项");
        return false;
      }
    });
  }
};
const initData = () => {
  // let key: keyof GatewayInstance;

  form.id = props.detailData.id;
  form.name = props.detailData.name;
  form.description = props.detailData.description;
  form.routeId = props.detailData.routeId;
  selectedType.value = props.detailData.type; // 那个类型单独设置
  if (props.detailData.flowControlConfig) {
    let flowControlConfig = JSON.parse(props.detailData.flowControlConfig);
    form.rate = flowControlConfig.rate;
    form.burst = flowControlConfig.burst;
    form.key = flowControlConfig.key;
    form.conn = flowControlConfig.conn;
    form.default_conn_delay = flowControlConfig.default_conn_delay;
  }
  // for(key in form){
  //   form[key] = props.detailData[key];
  // }
};

// 获取路由和后端服务列表的数据
const getRouterAndBackService = async () => {
  let res = await getRouterManagerList({
    page: 1,
    pageSize: 10,
    name: "路由"
  });
  optionsRouter.value = res.dataList.map((item: any) => {
    return {
      label: item.name,
      value: item.id
    };
  });
};

onMounted(() => {
  if (!isCreate.value) {
    initData();
  }
  getRouterAndBackService();
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  padding: 10px;
}
.el-form {
  margin: 0 auto;
}
</style>
